package com.nian.message.rocketmq.producer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/6 0006 22:46
 */
@Slf4j
@Component
@RocketMQTransactionListener
public class RocketMQTransactionLocalListenerSimple implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try{
            String jsonString = new String((byte[]) message.getPayload());
            log.info("executeLocalTransaction 事务监听：");
            String txId = String.valueOf(message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID));
            log.info("executeLocalTransaction 事务ID: {} ", txId);
            log.info("executeLocalTransaction {}", jsonString);
            log.info("executeLocalTransaction {}", message.getHeaders());
            log.info("executeLocalTransaction All: {}", JSONObject.toJSONString(message));
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        final JSONObject jsonObject = JSON.parseObject(new String((byte[]) message.getPayload()));
        log.info("check 事务ID 检查：{}",jsonObject);
        //事务id
        String txId = String.valueOf(message.getHeaders().get("transactionId"));
        log.info("check 事务ID: {} ", txId);
        // 假设成功
        int c = 1;
        log.info("check 事务ID: {} 结果: {}", txId, c);
        if (c > 0) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
